<?php
/*
 * @Descripttion:
 * @version:
 * @Author: ewgof
 * @Date: 2020-08-12 00:24:23
 * @LastEditors: ewgof
 * @LastEditTime: 2020-10-25 16:53:19
*/

use Workerman\Worker;

$db = null;
$clientid = '';
global $db,$clientid;

// 创建一个Worker监听2345端口，使用http协议通讯
$http_worker = new Worker("http://0.0.0.0:2345");

// 启动4个进程对外提供服务
$http_worker->count = 4;

$http_worker->onConnect = function ($connection) {
    // 生成当前连接的唯一性id，主要用于缓存数据的存取,长连接应用在这里生成 clientid
    // global $clientid;
    // $clientid = make_clientid($connection->id);
    // var_dump('on start clientid  : ' . $clientid);
};

$http_worker->onWorkerStart = function ($connection) {
    global $db;
    
    $db = db_connect();

    $website_config = $db->get('website_config', ['key_words', 'description', 'favicon', 'logo', 'user_upload_size', 'user_upload_number', 'guest_upload_size', 'guest_upload_number']);
    if (empty($website_config)) {
        $website_config = [
            'key_words' => '',
            'description' => '',
            'favicon' => __ROOT__ . 'favicon.icon',
            'logo' => '',
            'user_upload_size' => USER_UPLOAD_SIZE,
            'user_upload_number' => USER_UPLOAD_NUMBER,
            'guest_upload_size' => GUEST_UPLOAD_SIZE,
            'guest_upload_number' => GUEST_UPLOAD_NUMBER,
        ];
    }
    \cw\facade\Cache::set('website_config', $website_config);
};

// 接收到浏览器发送的数据
$http_worker->onMessage = function ($connection, $request) {
    if (strtolower($request->method()) == 'options') {
        send($connection);
        return ;
    }
    $token = '';
    if (
        strpos($request->path(), '/upload') === false &&
        strpos($request->path(), '/favicon') === false &&
        strpos($request->path(), '/guestimgs') === false &&
        strpos($request->path(), '/login') === false
        ) {
        $token = $request->header('token');
    }
    // 查验 request
    $res = check_request($request->header('rtime'), $token);
    if ($res !== true) {
        send($connection, $res);
        // $connection->send($res);
        return ;
    }

    // 对请求进行路由分发
    route($connection, $request);
};


$http_worker->onWorkerStop = function ($connection) {
    global $db;
    unset($db);
};


$http_worker->onClose = function ($connection) {
    global $clientid;
    // \cw\facade\Cache::clean(true);
    unset($clientid);
};

// 如果不是在根目录启动，则运行runAll方法
if (!defined('GLOBAL_START')) {
    Worker::runAll();
}
